package com.jxt.detect;

import android.os.BatteryManager;

import androidx.annotation.NonNull;

import java.util.Objects;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
    private OfflineAmap offlineMap;

    @Override
    protected void onDestroy() {
        if (offlineMap != null) offlineMap.destroy();
        super.onDestroy();
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine){
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        BinaryMessenger binaryMessenger = flutterEngine.getDartExecutor().getBinaryMessenger();
        final MethodChannel appChannel = new MethodChannel(binaryMessenger, "AppChannel");
        appChannel.setMethodCallHandler((@NonNull MethodCall call, @NonNull MethodChannel.Result result) -> {
            try {
                switch (call.method) {
                    case "downloadOffline":
                        offlineMap = offlineMap == null ? new OfflineAmap(getApplicationContext(), appChannel, call.argument("cityName")) : offlineMap;
                        offlineMap.startDownload();
                        result.success(true);
                        break;
                    case "batteryLevel":
                        BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
                        Integer batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
                        Log.i("电池电量 => ", String.valueOf(batteryLevel));
                        result.success(Math.min(100, Math.max(0, batteryLevel)));
                        break;
                    default:
                        result.success(moveTaskToBack(true));
                        break;
                }
            } catch (Exception e) {
                Log.i("AppChannel异常", Objects.requireNonNull(e.getMessage()));
                e.printStackTrace();
            }
        });
    }
}
